<template>
  <div class="ind-post-form">
    <div class="ind-view" v-for="(indItem, indIdx) in list" :key="indIdx">
      <collapse-view :collapsible="indItem.header.collapse === 1" class="ind-card-item">
        <div class="title-view" v-if="indItem.header" slot="title">
          <div class="col-title">
            {{ indItem.header.title }}
            <el-tooltip
              v-if="
                rollbackable &&
                [INDICATION_STATUS.finished, INDICATION_STATUS.delayFinished].includes(indItem.header.status)
              "
              class="item"
              effect="dark"
              content="点击撤回本次填报"
              placement="top">
              <i class="iconfont kh-return" @click.stop="onRollback(indItem)"></i>
            </el-tooltip>
          </div>
          <div v-if="indItem.header.cycle" class="cycle">推送周期：{{ indItem.header.cycle }}</div>
          <div class="ind-post-status" :class="STATUS_TAG[indItem.header.status]">
            {{ indItem.header.status | statusDisplay }}
          </div>
        </div>
        <div v-if="indItem.displaySections && indItem.displaySections.length">
          <form-display
            v-for="(pItem, pIdx) in indItem.displaySections"
            :key="pIdx"
            :form-idx="pIdx"
            :form-data="pItem.data"></form-display>
        </div>
        <template v-if="indItem.postConfig">
          <form-share-info
            v-if="indItem.postConfig.share"
            :share-info="indItem.postConfig.share"
            :disabled="indItem.postConfig.disabled"
            @share-count-change="shareCount => onFromShareChange(indItem.postConfig, shareCount)"></form-share-info>
          <template v-if="showEditForms(indItem.postConfig)">
            <form-edit
              v-for="(formItem, formIdx) in indItem.postConfig.forms"
              :key="formItem.id"
              :id="formItem.id"
              :form-idx="formIdx"
              :fields="indItem.postConfig.fields"
              :field-data="formItem.fieldData"
              :pid="formItem.pid"
              :share-count="indItem.postConfig.share && indItem.postConfig.share.value"
              :disabled="indItem.postConfig.disabled"
              :show-delete="indItem.postConfig.multi && formIdx > 0"
              :show-add="
                indItem.postConfig.multi &&
                (!indItem.postConfig.multi.max ||
                  indItem.postConfig.multi.max >
                    ((indItem.postConfig.share && indItem.postConfig.share.value) || 0) +
                      indItem.postConfig.forms.length) &&
                formIdx === indItem.postConfig.forms.length - 1
              "
              @change="data => onFormChange(formItem, data)"
              @form-add="onFormAdd(indItem.postConfig)"
              @form-delete="onFormDelete(indItem.postConfig.forms, formIdx)"></form-edit>
          </template>
        </template>
        <template v-if="indItem.children">
          <ind-post-form
            :list="indItem.children"
            :pushable="pushable"
            :is-root="false"
            @form-change="$emit('form-change')"
            @item-save="saveFormData"></ind-post-form>
        </template>
        <div v-if="indItem.emptyTips" class="empty-tips">{{ indItem.emptyTips }}</div>
      </collapse-view>
      <div
        class="post-btn-view"
        v-if="
          pushable &&
          [INDICATION_STATUS.init, INDICATION_STATUS.delay].includes(indItem.header.status) &&
          !(indItem.postConfig && indItem.postConfig.disabled)
        ">
        <el-button size="small" @click="saveFormData(false, indItem)">暂存</el-button>
        <el-button type="primary" size="small" @click="saveFormData(true, indItem)">提交</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { rollbackIndPost } from '@api/modules/indication.js'
import { INDICATION_STATUS, IND_POST_TYPE } from '@utility/dict'
import CollapseView from '@com/CollapseView.vue'
import FormDisplay from './components/FormDisplay.vue'
import FormEdit from './components/FormEdit.vue'
import FormShareInfo from './components/FormShareInfo.vue'
import { guid } from '@utility/utility'

export default {
  name: 'IndPostForm',
  components: { CollapseView, FormDisplay, FormEdit, FormShareInfo },
  props: {
    list: {
      type: Array,
    },
    indIndex: {
      type: Number,
      default: 0,
    },
    isRoot: {
      type: Boolean,
      default: true,
    },
    pushable: {
      type: Boolean,
      default: false,
    },
    rollbackable: {
      type: Boolean,
    },
  },
  data() {
    return {
      STATUS_TAG: INDICATION_STATUS._tag,
      INDICATION_STATUS: INDICATION_STATUS._define,
    }
  },
  filters: {
    statusDisplay(val) {
      return INDICATION_STATUS[val]
    },
  },
  computed: {
    // rollbackable() {
    //   let inRollbackTime = false
    //   if (this.schemeInfo && this.schemeInfo.recallStart && this.schemeInfo.recallEnd) {
    //     const now = new Date()
    //     const startDate = new Date(this.schemeInfo.recallStart)
    //     const endDate = new Date(this.schemeInfo.recallEnd)
    //     if (now >= startDate && now <= endDate) {
    //       inRollbackTime = true
    //     }
    //   }
    //   return this.pushable && inRollbackTime
    // },
  },
  watch: {},
  created() {
    if (this.list) {
      this.list.forEach(item => {
        if (item.postConfig) {
          this.initMaxShareFormData(item.postConfig)
        }
      })
    }
  },
  mounted() {},
  methods: {
    showEditForms(postConfig) {
      const { share, multi } = postConfig
      if (share) {
        if (multi && multi.max) {
          if (share.value < multi.max) {
            return true
          } else {
            return false
          }
        } else {
          return share.value === 0
        }
      }
      return true
    },
    initMaxShareFormData(postConfig) {
      const { share, multi } = postConfig
      if (share && multi && multi.max && share.value >= multi.max) {
        const fieldData = postConfig.forms[0] && postConfig.forms[0].fieldData
        if (fieldData) {
          const data = {}
          fieldData.forEach(item => {
            data[item.fillId] = {
              value: item.content,
              config: JSON.parse(item.specificJson),
            }
          })
          postConfig.forms[0].data = data
        }
      }
    },
    onFormChange(formItem, formData) {
      const isFirstInit = !formItem.data
      formItem.data = formData // cloneDeep(formData)
      !isFirstInit && this.$emit('form-change')
    },
    onFormAdd(postConfig) {
      const forms = postConfig.forms
      forms.push({
        id: guid(),
        pushId: postConfig.pushId,
        pid: postConfig.pid, // 关联指标上级id
        pidOrder: postConfig.pidOrder, // 根指标 order
        data: null,
        fieldData: [],
      })
    },
    onFormDelete(forms, deleteIdx) {
      forms.splice(deleteIdx, 1)
      this.$emit('form-change')
    },
    saveFormData(isSubmit, indItem) {
      this.$emit('item-save', isSubmit, indItem)
    },
    onFromShareChange(postConfig, shareCount) {
      const { forms, share, multi } = postConfig
      share.value = shareCount
      const shareFieldId = share.fillId
      forms.forEach(formItem => {
        for (const key in formItem.data) {
          if (key === shareFieldId) {
            const fieldItem = formItem.data[key]
            fieldItem.value = shareCount
          }
        }
        if (formItem.fieldData) {
          for (const key in formItem.fieldData) {
            const dataItem = formItem.fieldData[key]
            if (dataItem.fillId === shareFieldId) {
              dataItem.content = shareCount
            }
          }
        }
      })
      // TODO 应该将 share信息从form中剔除，需后台改结构
      // 多个forms时，根据当前选择项，修改forms
      if (multi) {
        const { max } = multi
        if (forms.length + shareCount > max) {
          let sholdPostCount = max - shareCount
          // 只保留一个from
          if (sholdPostCount <= 0) {
            sholdPostCount = 1
            // 并清空form内容
            for (const key in postConfig.forms[0].data) {
              const fieldItem = postConfig.forms[0].data[key]
              if (fieldItem.config.type !== IND_POST_TYPE.fromShare) {
                if (fieldItem.config.type === IND_POST_TYPE.file) {
                  fieldItem.value = []
                } else {
                  fieldItem.value = ''
                }
              }
              // postConfig.forms[0].fieldData = null
            }
          }
          postConfig.forms.splice(sholdPostCount)
        }
      } else if (shareCount === 1) {
        for (const key in postConfig.forms[0].data) {
          const fieldItem = postConfig.forms[0].data[key]
          if (fieldItem.config.type !== IND_POST_TYPE.fromShare) {
            if (fieldItem.config.type === IND_POST_TYPE.file) {
              fieldItem.value = []
            } else {
              fieldItem.value = ''
            }
          }
          // postConfig.forms[0].fieldData = null
        }
      }
      this.$emit('form-change')
    },
    onRollback(indItem) {
      console.log('indItem....', indItem)
      this.$confirm('确定要撤回该本次填报吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          // indItem
          rollbackIndPost(indItem.id).then(res => {
            if (res.code === 0) {
              this.$message.success('撤回成功！')
              this.$emit('rollback', indItem.isRelateInd)
            }
          })
        })
        .catch(() => {})
    },
  },
}
</script>
<style lang="scss" scoped>
.ind-post-form {
  &:not(:first-child) {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #ddd;
  }
  .ind-view {
  }
  .title-view {
    display: flex;
    align-items: center;
    font-size: 16px;
    width: 100%;
    overflow: hidden;
    .col-title {
      text-align: left;
      // overflow: hidden;
      // white-space: nowrap;
      // text-overflow: ellipsis;
      // word-break: break-all;
      flex: 1;
    }
    .cycle {
      font-size: 14px;
      color: #666;
    }
    .col-operate {
      margin-left: 20px;
      cursor: pointer;
      &:hover {
        opacity: 0.8;
      }
      &.add {
        color: #2c63b0;
      }
      &.delete {
        color: #f56c6c;
      }
    }
    .ind-post-status {
      font-size: 14px;
      margin-left: 10px;
      &.notStart {
        color: #909399;
      }
      &.init {
        color: #2c63b0;
      }
      &.delay {
        color: #f56c6c;
      }
      &.finished {
        color: #67c23a;
      }
      &.delayFinished {
        color: #67c23a;
      }
    }
    .kh-return {
      margin-left: 10px;
      padding: 2px;
      color: #fff;
      background: #e6a23c;
      border-radius: 50%;
      cursor: pointer;
    }
  }
  .ind-card-item {
    margin-bottom: 20px;
    background: #fff;
  }
  .post-btn-view {
    text-align: center;
    margin: 20px 0;
    .el-button {
      width: 100px;
    }
  }
  .empty-tips {
    text-align: center;
    color: #999;
    font-size: 16px;
  }
}
</style>
